/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3utils.
 *
 *  e3utils is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3utils is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3utils. If not, see <https://www.gnu.org/licenses/>.
 */

package load_balancer

type Mode int

const (
	RandMode Mode = iota //随机
	PollMode             //轮询
	BestMode             //最优
	HashMode             //一致性hash
)

type Context interface {
	LoadBalancerID() uint64
}

type Balancer[T Context] interface {
	Mode() Mode
	Count() int // register count
	Register(ctx T) error
	UnRegister(ctxID uint64) (T, bool)
	Clean() []T
	Range(func(T) bool)                   // Scan Context when return true
	TakeByID(ctxID uint64) (T, bool)      // return context with ID
	TakeNext(id uint64) (T, error)        // RandMode , BestMode and PollMode ignore id , HashMode use id on hash ring
	SetAutoPriWt(weight int16)            // BestMode set auto add priority weight, each time take. default value is 1
	UpdatePriWt(ctxID uint64, weight int) // BestMode the priority weight change. each time take, the priority weight value add by [AutoPriWt] auto. the lower the weight value, the higher the priority. the valid range is [minInt,maxInt]
}

func NewBalancer[T Context](m Mode) Balancer[T] {
	switch m {
	case PollMode:
		return NewBalancerPoll[T]()
	case BestMode:
		return NewBalancerBest[T]()
	case HashMode:
		return NewBalancerHash[T]()
	default:
		panic("new balancer ill mode")
	}
	return nil
}
